const fs   = require('fs');
const path = require('path')
const DIR  = `${path.dirname(__dirname)}/runtime/`;
const { env }    = process;
const unLockTime = env.UN_LOCK_TIME*1000;//毫秒

function judge(task = false){
    let isExists = fs.existsSync(DIR);
    try{
        if(!isExists){
            fs.mkdirSync(DIR);
        }
        const file = DIR+'.lock';
        if(task === false){
            let data = +fs.readFileSync(file).toString();
            if(data > 0){
                //加一次时间判断，防止程序出错锁死定时执行。
                let cTime = new Date().getTime();
                let mTime = fs.statSync(file).mtimeMs;
                if(mTime < cTime - unLockTime){
                    fs.writeFileSync(file,0);
                    return 0;
                }
            }
            return data;
        }

        return fs.writeFileSync(file,task);
    }catch(e){

    }

    return 0;
}

module.exports = judge;